package club.web51.classroom_tool.Services;

import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired ; 
import club.web51.classroom_tool.Repositories.SettingRepository;
import club.web51.classroom_tool.Utils.SFWhere;
import club.web51.classroom_tool.DO.sysDO.Setting;

import javax.annotation.Resource;

/**
 * 服务类
 * @author cxk
 * @since 1.0.0
 */
@Service
public class SettingService {
    @Resource
    SettingRepository settingRepository;
    /**
     * 根据Setting的字段自动生成条件,字段值为null不生成条件
     * 如果是数值型的字段,前端不传入值,默认是0,例如ID的类型是Long,如果不传值,默认是0
     * 可以自己设置下SFWhere.and(setting).equal(实体.getId()>0,"id",实体.getId()).build()
     * @param setting     实体对象
     * @param pageable 分页对象
     * @return 返回分页\状态码
     */
    public ResponseEntity<Object> search(Setting setting, Pageable pageable) {
        Page<Setting> all = settingRepository.findAll(SFWhere.and(setting)
                .build(), pageable);
        return new ResponseEntity<>(all, HttpStatus.OK);
    }

    public Msg updateOne(Setting setting){
        if(ObjectUtil.isNull(setting)){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        }
        if(ObjectUtil.isNull(setting.getId())){
            settingRepository.save(setting);
        }
        Setting setting1 = settingRepository.getOne(setting.getId());
        //仅允许修改值
        setting1.setValue(setting.getValue());
        settingRepository.save(setting1);
        return MsgUtil.success();
    }

    public Boolean existedByName(String name){
        return settingRepository.existsSettingByName(name);
    }

    public Msg deleteByName(String name){
        settingRepository.deleteByName(name);
        return MsgUtil.success();
    }
}
